# To change this template, choose Tools | Templates
# and open the template in the editor.


require 'net/http'
require 'uri'
require 'rubygems'
require 'dm-core'
require './logger.rb'
require './quote.rb'
require './settings.rb'

def download_from(url)
  return Net::HTTP.get(URI.parse(url))
end

def read_from_file(filename)
  res = File.open(filename, "r") { |f| f.read  }
  return res
end

def write_to_file(quotes)
  filename = "../data/MiniSP " + Time.now.strftime("%Y%m%d %H%M%S") + ".txt"
  f = File.new(filename, "w+")
  if quotes.nil?
    f.puts("quotes is nil")
  elsif quotes.respond_to?("each")
    quotes.each do |quote|
      f.puts quote.to_s
    end
  else
    f.puts(quotes)
  end
end

def write_to_db(quotes)
  if quotes.respond_to?("each")
    last_db_quote = Quote.first(:order => [ :Id.desc ])
    first_quote = quotes[0]

    if(not last_db_quote.nil?)
      Logger.instance.log_with_timestamp("DB last quote: " + last_db_quote.Datetime.to_s)
    end
    if(not first_quote.nil?)
      Logger.instance.log("Downloaded first quote: " + first_quote.Datetime.to_s)
    end

    if(last_db_quote.nil? or first_quote.Datetime > last_db_quote.Datetime)
      quotes.each do |quote|
        quote.save
      end
    end

  end
end

DataMapper.setup(:default, Settings.get_dbconnection_string )
DataMapper.finalize

logger = Logger.instance
logger.log_with_timestamp("Start")
url = Settings.get_url
url += Time.now.to_i.to_s

logger.log_with_timestamp("Downloading... ")

#PRODUCTION
res = download_from url
#-------------------->

#DEBUG
#res = read_from_file '../data/data20110210 055053.txt'
#-------------------->

logger.log_with_timestamp("Downloading is finished")

fdownloaded = File.open("../log/downloaded/data"+Time.now.strftime("%Y%m%d %H%M%S")+".txt", "a")
fdownloaded.puts(res)
fdownloaded.flush()

logger.log_with_timestamp("Processing data...")

lines = res.split("<br>")
logger.log_with_timestamp("Spliting is finished")

s_quotes = nil
if lines.respond_to?("each")
  s_quotes = Array.new()
  lines.each do |line|
    begin
      s_quotes.push Quote.new(line)
    rescue
      if line.strip.length > 0
        logger.log_with_timestamp("Warning! Cannot parse next line :\n" + line)
        logger.log("")
      end
    end
  end
else
  logger.log_with_timestamp("Warning! Did not split on lines")
  s_quotes = lines
end

logger.log_with_timestamp("Writing quotes to DB")
write_to_db s_quotes

logger.log_with_timestamp("Writing quotes to file")
write_to_file s_quotes

logger.log_with_timestamp("Done.")
logger.log("")
